package modules

type TableOfContentsItem struct {
	ID       string
	Text     string
	Children []TableOfContentsItem
}

type TableOfContentsProps struct {
	Items []TableOfContentsItem
}

templ TableOfContents(props TableOfContentsProps) {
	<aside
		class="text-sm"
		data-toc="container"
	>
		<div class="px-4 mb-6">
			<a href="mailto:hello@axeladrian.com?subject=templUI%20Sponsorship" class="block border rounded-md p-3 hover:border-muted-foreground/50 transition-colors group">
				<p class="text-[0.65rem] font-medium uppercase tracking-wider text-muted-foreground mb-2">Sponsored</p>
				<div class="flex items-center justify-center h-8 opacity-60 group-hover:opacity-80 transition-opacity">
					<span class="text-[0.7rem] text-muted-foreground">Your Brand Here</span>
				</div>
			</a>
		</div>
		if len(props.Items) > 0 {
			<div class="flex flex-col gap-2 p-4 pt-0">
				<p class="text-xs text-muted-foreground sticky top-0 bg-background py-2">On This Page</p>
				<nav class="flex flex-col gap-0.5">
					@renderTOCItems(props.Items, 0)
				</nav>
			</div>
		}
	</aside>
}

templ renderTOCItems(items []TableOfContentsItem, level int) {
	for _, item := range items {
		<a
			href={ templ.SafeURL("#" + item.ID) }
			class={ templ.Classes(
				"block py-1 text-[0.8rem] text-muted-foreground hover:text-foreground",
				"no-underline transition-colors break-words",
				templ.KV("pl-4", level == 1),
				templ.KV("pl-6", level >= 2),
			) }
			data-toc-link="true"
			data-section-id={ item.ID }
		>
			{ item.Text }
		</a>
		if len(item.Children) > 0 {
			@renderTOCItems(item.Children, level+1)
		}
	}
}

templ TableOfContentsScript() {
	<script defer nonce={ templ.GetNonce(ctx) }>
        document.addEventListener('DOMContentLoaded', () => {
            const toc = document.querySelector('[data-toc="container"]');
            const main = document.querySelector('main.overflow-y-auto');
            if (!toc || !main) return;

            toc.addEventListener('click', (e) => {
                const link = e.target.closest('[data-toc-link]');
                if (!link) return;

                e.preventDefault();
                const section = document.getElementById(link.dataset.sectionId);
                if (section) main.scrollTo({ top: section.offsetTop - 100 });
            });
        });
    </script>
}
